from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest


class AsyncImageLoader:
    def __init__(self, image_urls, callback, index=0):
        self.manager = QNetworkAccessManager()
        self.callback = callback
        self.image_urls = image_urls

        if index > 0:
            self.load_image(index-1)
        else:
            self.load_image()

    def load_image(self, i=0):
        url = self.image_urls[i]
        request = QNetworkRequest(QUrl(url))
        reply = self.manager.get(request)
        reply.finished.connect(lambda r=reply, i=i: self.on_image_finished(r, i))

    def on_image_finished(self, reply, i):
        url = self.image_urls[i]
        print(url)
        error = reply.error()
        if error:
            print(f"Error downloading {url}: {reply.errorString()}")
            return

        image = QImage.fromData(reply.readAll())
        if not image.isNull():
            self.callback(image, i)
        reply.deleteLater()

        if i < len(self.image_urls) - 1:
            self.load_image(i+1)

